package com.bxd.baodan.receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

import com.google.gson.Gson;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.j256.ormlite.dao.Dao;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.AnswerDetailActivity;
import com.bxd.baodan.activity.InsuranceActivity;
import com.bxd.baodan.activity.MainActivity;
import com.bxd.baodan.activity.QuestionDetailActivity;
import com.bxd.baodan.activity.WebViewPager;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.app.SharedPreferanceKey;
import com.bxd.baodan.db.DBHelper;
import com.bxd.baodan.item.MessageItem;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.Utils;

import org.json.JSONException;
import org.json.JSONObject;

public class PushDemoReceiver extends BroadcastReceiver {

    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView ==
     * null)
     */
    public static StringBuilder payloadData = new StringBuilder();

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        LogUtil.e("onReceive() action=" + bundle.getInt("action"));
        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                // 获取透传数据
                byte[] payload = bundle.getByteArray("payload");
                String taskid = bundle.getString("taskid");
                String messageid = bundle.getString("messageid");
                // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
                boolean result = PushManager.getInstance().sendFeedbackMessage(
                        context, taskid, messageid, 90001);
                if (result) {
                    LogUtil.e("push 注册成功");
                } else {
                    LogUtil.e("push 注册失败");
                }
                if (payload != null) {
                    String data = new String(payload);

                    payloadData.append(data);
                    payloadData.append("\n");
                    try {
                        JSONObject json = new JSONObject(data);
                        int type = json.getInt("type");
                        onTextMessage(context, type, data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                break;

            case PushConsts.GET_CLIENTID:
                // 获取ClientID(CID)
                // 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
                String cid = bundle.getString("clientid");
                break;

            default:
                break;
        }
    }

    public void onTextMessage(Context context, int type, String message) {
        LogUtil.e("push message-:" + message);

        switch (type) {

            case Constant.MSG_NEW_ACTIVITIES:
            case Constant.MSG_NEW_READ:
            case Constant.MSG_NEW_BAODAN:
            case Constant.MSG_NEW_ANSWER:
            case Constant.MSG_NEW_ANSWER_ADD:

                notificationMessage(context, message);
                // 发送广播
                break;
            default:
                break;
        }

    }

    /**
     * 通知消息
     */
    private void notificationMessage(Context context, String content) {
        String title = "";
        int msgType = -1;
        Intent updateMsg = new Intent(Constant.ACTION_RECEIVE_MSG);
        try {
            msgType = new JSONObject(content).getInt("type");
            switch (msgType) {

                case Constant.MSG_NEW_ACTIVITIES: //新活动
                    title = new JSONObject(content).getString("title");
                    updateMsg.putExtra("msg_kind", Constant.MSG_NEW_ACTIVITIES);
                    SpUtil.getInstance().savaBoolean(
                            SharedPreferanceKey.IS_ACTIIVTED, true);

                    break;
                //
                case Constant.MSG_NEW_BAODAN:  //保单消息
                    title = new JSONObject(content).getString("title");
                    updateMsg.putExtra("msg_kind", Constant.MSG_NEW_BAODAN);
                    break;


                case Constant.MSG_NEW_READ:  //微阅读
                    title = new JSONObject(content).getString("title");
                    updateMsg.putExtra("msg_kind", Constant.MSG_NEW_READ);
                    break;

                case Constant.MSG_NEW_ANSWER:  //有新回答
                    title = new JSONObject(content).getString("title");
                    updateMsg.putExtra("msg_kind", Constant.MSG_NEW_ANSWER);
                    break;
                case Constant.MSG_NEW_ANSWER_ADD:  //有新回答
                    title = new JSONObject(content).getString("title");
                    updateMsg.putExtra("msg_kind", Constant.MSG_NEW_ANSWER_ADD);
                    break;

                default:
                    break;
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        LogUtil.e("receiver message " + content);
        try {
            /**
             * 将消息存到数据库
             */
            Dao<MessageItem, String> dao = DBHelper.getInstance(context)
                    .getDao(MessageItem.class);
            MessageItem item = new Gson().fromJson(content, MessageItem.class);

            if (LoginInfo.getInstance(context).getUser().getU_id() != null
                    && (item.getType() == Constant.MSG_NEW_ANSWER || item.getType() == Constant.MSG_NEW_ANSWER_ADD)) {
                item.setUid(LoginInfo.getInstance(context).getUser().getU_id());
            }
            item.setUserString(item.getUserString());
            item.setTime(System.currentTimeMillis());


            Class clazz = MainActivity.class;
            Intent resultIntent = new Intent();
            resultIntent.putExtra("MessageItem", item);
            switch (msgType) {

                case Constant.MSG_NEW_ACTIVITIES: //新活动
                    // TODO 修改为内容字段
                    item.setContent(new JSONObject(content).getString("content"));
                    item.setType(Constant.MSG_NEW_ACTIVITIES);
                    dao.createOrUpdate(item);
                    clazz = WebViewPager.class;
                    if (item.getUrl() != null && !item.getUrl().equals("")) {
                        resultIntent.setClass(context, clazz);
                        resultIntent.putExtra("startUrl", item.getUrl());
                    }
                    break;


                case Constant.MSG_NEW_READ:  //微阅读
                    item.setContent(new JSONObject(content).getString("content"));
                    item.setType(Constant.MSG_NEW_READ);
                    dao.createOrUpdate(item);
                    clazz = WebViewPager.class;
                    if (item.getUrl() != null && !item.getUrl().equals("")) {
                        resultIntent.setClass(context, clazz);
                        resultIntent.putExtra("startUrl", item.getUrl());
                    }
                    break;


                case Constant.MSG_NEW_BAODAN:  //保单
                    item.setContent(new JSONObject(content).getString("content"));
                    item.setType(Constant.MSG_NEW_BAODAN);
                    dao.createOrUpdate(item);
                    clazz = InsuranceActivity.class;
                    if (item.getBdId() != null && !item.getBdId().equals("")) {
                        resultIntent.setClass(context, clazz);
                        resultIntent.putExtra("params", item.getBdId());
                    }
                    break;

                default:
                    break;
                case Constant.MSG_NEW_ANSWER:  //有新回答
                    item.setContent(new JSONObject(content).getString("content"));
                    item.setType(Constant.MSG_NEW_ANSWER);
                    dao.createOrUpdate(item);
                    clazz = QuestionDetailActivity.class;
                    if (item.getQid() != -1) {
                        resultIntent.setClass(context, clazz);
                        resultIntent.putExtra("qid", item.getQid() + "");
                    }
                    break;

                case Constant.MSG_NEW_ANSWER_ADD:  //有新回答
                    item.setContent(new JSONObject(content).getString("content"));
                    item.setType(Constant.MSG_NEW_ANSWER_ADD);
                    dao.createOrUpdate(item);
                    clazz = AnswerDetailActivity.class;
                    //推送消息需要加上PARENT_ACTIVITY
                    /* <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".activity.MainActivity"/>*/

                    //aid 回答id  qid 问题id
                    if (item.getAid() != -1 && item.getQid() != -1) {
                        resultIntent.setClass(context, clazz);
                        resultIntent.putExtra("qaid", item.getAid() + "");
                        resultIntent.putExtra("qid", item.getQid() + "");
                    }
                    break;


                //                case Constant.MSG_NEW_VIDEO:  //小视频
                //                    item.setContent(new JSONObject(content).getString("content"));
                //                    item.setType(Constant.MSG_NEW_VIDEO);
                //                    dao.createOrUpdate(item);
                //                    clazz = VideoDetailActivity.class;
                //                    if (item.getQid() != -1) {
                //                        resultIntent.setClass(context, clazz);
                //                        resultIntent.putExtra("video_id", item.getA_id());
                //
                //                    }
                //                    break;
                //                case Constant.MSG_NEW_RECEIPT:  //消息回执
                //                    if (LoginInfo.getInstance(context).getUser().getU_id() == null)
                //                        return;
                //                    item.setType(Constant.MSG_NEW_RECEIPT);
                //                    dao.createOrUpdate(item);
                //                    String uid = LoginInfo.getInstance(context).getUser()
                //                            .getU_id();
                //                    clazz = WebViewPager.class;
                //                    resultIntent.setClass(context, clazz);
                //                    resultIntent.putExtra("startUrl", Constant.FEEDBACK_URL + "uid="
                //                            + uid + "&data=" + Utils.deviceJson(context)
                //                            + "&kind=0");
                //                    break;


            }

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                    context).setSmallIcon(R.drawable.tongzhi_icon)
                    .setContentTitle(title).setContentText(item.getContent())
                    .setAutoCancel(true);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(clazz);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                    0, PendingIntent.FLAG_CANCEL_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);


            NotificationManager mNotificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);


            //创建消息提醒参数
            Notification nft = mBuilder.build();
            Uri alert = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            nft.sound = alert;
            nft.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL;
            nft.ledARGB = 0xff0000ff;
            nft.ledOnMS = 300;
            nft.ledOffMS = 300;
            // 判断是否状态栏提示
            if (Constant.MSG_DEVICE_RELOGIN == msgType) {
                mNotificationManager.notify(100251, nft);
            } else {
                if (!Utils.isNotDisturbOn()) {
                    //消息提醒
                    mNotificationManager.notify(item.getQid() + "_" + item.getAid(), item.getQid(), nft);
                }
            }
            context.sendBroadcast(updateMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
